<template>
  <div
    class="playBox"
    ref="playBox"
    :style="{
      gridTemplateColumns: layout[spiltIndex].columns,
      gridTemplateRows: layout[spiltIndex].rows,
      gap: '4px',
      backgroundColor: '#a9a8a8'
    }"
  >
    <div
      v-for="i in layout[spiltIndex].spilt"
      :key="i"
      class="play-box"
      :class="getPlayerClass(spiltIndex, i)"
      @click="playerIdx = i - 1"
    >
      <easyPlayer :url="videoUrl[i - 1]"></easyPlayer>
    </div>
  </div>
</template>

<script>

import easyPlayer from "./easyPlayer.vue";
import screenfull from "screenfull";
 import {dvGetPreviewURL,dvGetPlaybackURLs} from "@/api/pageViewBig"
//   import { witnessDeviceStopPlay} from "@/api/videoPage.js"
export default {
   props:{
 
      spiltIndex:{
         type:Number,
         default:1
      }
   },
  data() {
    return {
      time:null,
      videoUrl: [""],
      loading: false,
      layout: [
        {
          spilt: 1,
          columns: "1fr",
          rows: "1fr",
          style: function () {}
        },
        {
          spilt: 4,
          columns: "1fr 1fr",
          rows: "1fr 1fr",
          style: function () {}
        },
        {
          spilt: 6,
          columns: "1fr 1fr 1fr",
          rows: "1fr 1fr 1fr",
          style: function (index) {
            if (index === 0) {
              return {
                gridColumn: " 1 / span 2",
                gridRow: " 1 / span 2"
              };
            }
          }
        },
        {
          spilt: 9,
          columns: "1fr 1fr 1fr",
          rows: "1fr 1fr 1fr",
          style: function () {}
        },
        {
          spilt: 16,
          columns: "1fr 1fr 1fr 1fr",
          rows: "1fr 1fr 1fr 1fr",
          style: function () {}
        }
      ],
      playerIdx: 0, //激活播放器
      updateLooper: 0 //数据刷新轮训标志
    };
  },
  computed: {
    liveStyle() {
      let style = { width: "100%", height: "100%" };
      switch (this.spilt) {
        case 4:
          style = { width: "49%", height: "49%" };
          break;
        case 9:
          style = { width: "32%", height: "32%" };
          break;
      }
      this.$nextTick(() => {
        for (let i = 0; i < this.spilt; i++) {
          const player = this.$refs.player;
          player && player[i] && player[i].updatePlayerDomSize();
        }
      });
      return style;
    }
  },
  watch: {
    spilt(newValue) {
      console.log("切换画幅;" + newValue);
      let that = this;
      for (let i = 1; i <= newValue; i++) {
        if (!that.$refs["player" + i]) {
          continue;
        }
        this.$nextTick(() => {
          if (that.$refs["player" + i] instanceof Array) {
            that.$refs["player" + i][0].resize();
          } else {
            that.$refs["player" + i].resize();
          }
        });
      }
      window.localStorage.setItem("split", newValue);
    },
    "$route.fullPath": "checkPlayByParam"
  },
  components: {
    easyPlayer
  },
  destroyed() {
    clearTimeout(this.updateLooper);
    this.handleStopPlay();
  },
  created() {

  },
  methods: {

    checkPlayByParam() {
      let channelId = this.$route.query;
      if (channelId) {
        this.sendDevicePush(channelId);
      }
    },
    setPlayUrl(url, idx) {
        this.$set(this.videoUrl, idx, url)
        let _this = this
        setTimeout(() => {
          window.localStorage.setItem('videoUrl', JSON.stringify(_this.videoUrl))
        }, 100)
  
      },
    // 关闭视频播放按钮
    handleStopPlay() {
      const extractString = (str, start, end) => {
        let startIndex = str.indexOf(start);
        let endIndex = str.indexOf(end, startIndex + start.length);
        return str.substring(startIndex !== -1 && endIndex !== -1 ? startIndex + start.length : 0, endIndex);
      };
      let newURLs = new Set([]);
      this.videoUrl.forEach((x) => {
        newURLs.add(extractString(x, "live/", ".live"));
      });
      // witnessDeviceStopPlay([...newURLs]).then((res) => {
      //   console.log(res);
      // });
    },
    getPlayerClass(splitIndex, i) {
      let classStr = "play-box-" + splitIndex + "-" + i;
      if (this.playerIdx === i - 1) {
        classStr += " redborder";
      }
      return classStr;
    },
    clickEvent(channelId) {
      // console.log('channelId',channelId);
      this.sendDevicePush(channelId);
    },
    // 批量播放设备
    sendDevicePushAll(channelIds,time = null) {
      this.time = time
      let num = 0
      const lenght =  channelIds.length
      if (lenght > 12){
        num = 4
      }
      if(9 < lenght <= 12){
        num = 4
      }
      if(6 < lenght <= 9 ){
        num = 3
      }
      if(4<lenght<=6){
        num = 2
      }
      if(lenght<=4){
        num = 1
      }
      this.$emit('update:spiltIndex',num)
      channelIds.forEach((x,index) => {
        this.sendDevicePush(x,index);
      });
      },
    //通知设备上传媒体流
   async sendDevicePush(channelId,idx) {
      this.save(channelId);
      let idxTmp = idx || this.playerIdx;
      let result = null
      let videoUrl = null
      if(this.time){
       const [startTime,endTime] = this.time
        const params = {
          "deviceId":channelId,
          "startTime": startTime,
          "endTime": endTime
        }
        result = await dvGetPlaybackURLs(params)
       
      }else{
      
        result = await  dvGetPreviewURL(channelId)
      }
      if(result.code === 0 && result.data.url){
        if (location.protocol === "http:") {
              videoUrl = result.data.url;
            } else {
              videoUrl = result.data.url;
            }
            this.setPlayUrl(videoUrl, idxTmp);
         }
    },
    save(item) {
      let dataStr = window.localStorage.getItem("playData") || "[]";
      let data = JSON.parse(dataStr);
      data[this.playerIdx] = item;
      window.localStorage.setItem("playData", JSON.stringify(data));
    },
    destroy(idx) {
      this.clear(idx.substring(idx.length - 1));
    },
    fullScreen: function () {
      if (screenfull.isEnabled) {
        screenfull.toggle(this.$refs.playBox);
      }
    },
    shot(e) {
      // console.log(e)
      // send({code:'image',data:e})
      var base64ToBlob = function (code) {
        let parts = code.split(";base64,");
        let contentType = parts[0].split(":")[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {
          type: contentType
        });
      };
      let aLink = document.createElement("a");
      let blob = base64ToBlob(e); //new Blob([content]);
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = "截图";
      aLink.href = URL.createObjectURL(blob);
      aLink.click();
    }
  }
};
</script>

<style lang="scss" scoped>
.playBox{
    display: grid;
    justify-self: center;
    box-sizing: border-box;
   
}
.redborder {
  border: 4px solid rgb(0, 198, 255) !important;
  
  
}
.play-box {
  background-color: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
  

}
.play-box-2-1 {
  grid-column: 1 / span 2;
  grid-row: 1 / span 2;
}
</style>